﻿using Microsoft.IdentityModel.Tokens;
using SimpleInOutControl.Common;
using SimpleInOutControl.DBModels;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace SimpleInOutControl.Utility
{
    /// <summary>
    /// JWT工具类
    /// </summary>
    public class JwtUtils
    {
        /// <summary>
        /// 创建一个Token方法
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public static string CreateToken(UserInfo userInfo)
        {
            //1、准备有效载荷--写入需要写入的用户信息
            List<Claim> claims = new List<Claim>();
            var type = userInfo.GetType();
            var properties = type.GetProperties().ToList();
            properties.ForEach(property =>
            {
                var value = property.GetValue(userInfo);
                if (value != null)
                {
                    if (property.Name.ToLower() != "password")
                    {
                        if (value is string || value.GetType().IsValueType)
                        {
                            claims.Add(new Claim(property.Name, value.ToString()));
                        }
                        else
                        {
                            claims.Add(new Claim(property.Name, value.ToJson()));
                        }
                    }
                }
            });

            //2、准备加密解密key
            //SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtTokenOptions.SecurityKey));
            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("简易进出管理系统"));

            //3、选择加密算法
            SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);//使用加密key，选定加密算法

            //4、开始准备生成token
            JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(
                //issuer: _jwtTokenOptions.Issuer,
                //audience: _jwtTokenOptions.Audience,
                claims: claims.ToArray(),
                //expires: DateTime.Now.AddMinutes(5),//5分钟有效
                expires: DateTime.Now.AddHours(4),//5分钟有效
                signingCredentials: creds
                );

            //5、生成token
            var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

            return token;
        }

        public static bool CheckToken(string token)
        {
            ////1、准备加密解密key
            //SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtTokenOptions.SecurityKey));

            ////2、选择加密算法
            //SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);//使用加密key，选定加密算法

            if (string.IsNullOrEmpty(token))
            {
                throw new KeyNotFoundException("请求[header]中缺少Authoritarian");
            }


            //解析token内容（到此时说明已经验证token成功，直接解析荷载内容即可）
            var jwtSecurityToken = new JwtSecurityTokenHandler().ReadJwtToken(token);
            //var sss = jwtSecurityToken.Claims.Where(u => u.Type == "iss").FirstOrDefault().Value;
            //foreach (var claim in jwtSecurityToken.Claims)
            //{

            //}
            var exp = jwtSecurityToken.Claims.Where(u => u.Type == "exp").FirstOrDefault().Value;
            if (int.Parse(exp) < int.Parse( DataConvert.GetUnixTimeStamp()))
            {
                throw new KeyNotFoundException("无效Token或过期");
            }

            return true;
            //return jwtSecurityToken.Issuer;

        }
        //public string ReadToken1(string token)
        //{
        //    //1、准备加密解密key
        //    SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtTokenOptions.SecurityKey));

        //    //2、选择加密算法
        //    SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);//使用加密key，选定加密算法
        //    SecurityToken securityKey = null;
        //    var ss = new JwtSecurityTokenHandler().ValidateToken(token, new TokenValidationParameters()
        //    {

        //    }, out securityKey);
        //    //new JwtSecurityTokenHandler().valid
        //    //securityKey.
        //    //解析token内容（到此时说明已经验证token成功，直接解析荷载内容即可）
        //    var jwtSecurityToken = new JwtSecurityTokenHandler().ReadJwtToken(token);
        //    var sss = jwtSecurityToken.Claims.Where(u => u.Type == "iss").FirstOrDefault().Value;
        //    foreach (var claim in jwtSecurityToken.Claims)
        //    {

        //    }
        //    return jwtSecurityToken.Issuer;

        //}
    }
}
